//
//  FifthVideoDetailViewController.m
//  Project_B
//
//  Created by 张闯的mac pro on 15/11/29.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "FifthVideoDetailViewController.h"
#import "AFNetworkHandler.h"
#import "UIImageView+WebCache.h"
#import "FifthVideoModel.h"
#import "LazyFadeInView.h"
#import "CalculateHeight.h"
#import "FifthVideoPlayViewController.h"
#import "ShareTableView.h"
#import "FifthVideoViewController.h"
#import "UMSocial.h"
#import "CoreDataManager.h"
#import "Video.h"
#import "SDWebImageManager.h"
#import "ZCSTKPlayer.h"

@interface FifthVideoDetailViewController ()<UMSocialUIDelegate>


@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) BOOL insert;
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, strong) UIImage *img;
@property (nonatomic, strong) UIImageView *bottomImgView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) LazyFadeInView *fade;
@property (nonatomic, strong) UIButton *storeBtn;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation FifthVideoDetailViewController

- (void)dealloc
{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"加载" object:@"yes"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
//    if (self.i > self.modelArr.count - 2) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"加载" object:@"yes" userInfo:nil];
//    }
    //初始化单例manager
    self.coreDataManager = [CoreDataManager shareInstance];
    NSLog(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    
    if (self.dataArr == nil) {
        self.dataArr = [NSMutableArray array];
    }
    self.insert = NO;
//    [self downImage];
    [self initViews];
}

- (void)initViews
{
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375, 400)];
    [self.view addSubview:self.imgView];
    self.imgView.alpha = 0;
    [UIView animateWithDuration:2 animations:^{
        self.imgView.alpha = 1;
    }];
    
    UIButton *starBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    starBtn.frame = CGRectMake(173, 190, 50, 50);
    [starBtn setBackgroundImage:[UIImage imageNamed:@"playBtn@2x"] forState:UIControlStateNormal];
    [starBtn addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:starBtn];
    
    
    self.bottomImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,400, 375, 275)];
    self.bottomImgView.alpha = 1;
    [self.view addSubview:self.bottomImgView];
    self.bottomImgView.userInteractionEnabled = YES;
    
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(nextVideo)];
    [self.bottomImgView addGestureRecognizer:rightSwip];
    rightSwip.direction = UISwipeGestureRecognizerDirectionLeft;

    UISwipeGestureRecognizer *leftSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(lastVideo)];
    [self.bottomImgView addGestureRecognizer:leftSwip];
    leftSwip.direction = UISwipeGestureRecognizerDirectionRight;

    UISwipeGestureRecognizer *upSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(backAction)];
    upSwip.direction = UISwipeGestureRecognizerDirectionUp;
    [self.bottomImgView addGestureRecognizer:upSwip];
    
    //毛玻璃效果
    UIBlurEffect *effect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView=[[UIVisualEffectView alloc]initWithEffect:effect];
    effectView.frame= self.view.frame;
    [self.bottomImgView addSubview:effectView];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 300, 30)];
    [self.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    self.titleLabel.textColor = [UIColor whiteColor];
    [self.bottomImgView addSubview:self.titleLabel];

    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 45, 300, 1)];
    lineLabel.backgroundColor = [UIColor whiteColor];
    [self.bottomImgView addSubview:lineLabel];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 50, 100, 20)];
    [self.timeLabel setFont:[UIFont systemFontOfSize:14]];
    self.timeLabel.textColor = [UIColor whiteColor];
    [self.bottomImgView addSubview:self.timeLabel];
    
    self.fade = [[LazyFadeInView alloc] initWithFrame:CGRectMake(5, 75, 375 - 10, 100)];
    self.fade.textColor = [UIColor whiteColor];
    self.fade.numberOfLayers = 10;
    self.fade.interval = 0.04;
    [self.fade setTextFont:[UIFont systemFontOfSize:13]];
    [self.bottomImgView addSubview:self.fade];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    shareBtn.frame = CGRectMake(30, 197, 33, 33);
    [self.bottomImgView addSubview:shareBtn];
    [shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    [shareBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-share"] forState:0];
    
    self.storeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.storeBtn.frame = CGRectMake(80, 200, 30, 30);
    [self.storeBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:0];
    
    [self getMainData];
    [self setButtonImage];
    [self.bottomImgView addSubview:self.storeBtn];
    [self.storeBtn addTarget:self action:@selector(storeAction:) forControlEvents:UIControlEventTouchUpInside];
    
//    UIButton *downLoadBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//   // [self.bottomImgView addSubview:downLoadBtn];
//    downLoadBtn.frame = CGRectMake(130, 200, 30, 30);
//    downLoadBtn.backgroundColor = [UIColor whiteColor];
//    [downLoadBtn addTarget:self action:@selector(downLoadAction) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)changeShape
{
    [UIView animateWithDuration:2 animations:^{
        self.imgView.transform = CGAffineTransformScale(self.imgView.transform, 1.1, 1.1);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:2 animations:^{
            self.imgView.transform = CGAffineTransformScale(self.imgView.transform, 1 / 1.1, 1 / 1.1);
        } completion:^(BOOL finished) {
            return ;
        }];
    }];
}

- (void)storeAction:(UIButton *)sender
{
    self.dataArr = [NSMutableArray arrayWithArray:[self selectVideoModel]];

    if (self.dataArr.count == 0) {
        [self insertAction];
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:0];
    } else {
        
        [self.dataArr enumerateObjectsUsingBlock:^(Video *temp, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([[self.modelArr[self.i] title] isEqualToString:temp.title]) {
                self.insert = NO;
            } else {
                self.insert = YES;
            }
            
        }];
        
        if (self.insert) {
            [self insertAction];
            [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:0];
            
        } else {
            
            [self.dataArr enumerateObjectsUsingBlock:^(Video *temp, NSUInteger idx, BOOL * _Nonnull stop) {
                
                if ([[self.modelArr[self.i] title] isEqualToString:temp.title]) {
                    [self.coreDataManager.managedObjectContext deleteObject:temp];
                }
                
            }];

            [self.coreDataManager saveContext];
            [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-wodezuiai"] forState:0];
            self.insert = YES;
        }
    }
}


- (void)shareAction
{
    NSString *shareText = [NSString stringWithFormat:@"%@ %@ %@", [self.modelArr[self.i] title], [self.modelArr[self.i] video_description], [self.modelArr[self.i] playUrl]];             //分享内嵌文字
    
    //调用快速分享接口
    [UMSocialSnsService presentSnsIconSheetView:self
     
                                appKey:@"56396942e0f55a01aa00062c"
                                      shareText:shareText
                                     shareImage:self.img
                                shareToSnsNames:nil
                                       delegate:nil];
}

- (void)playAction
{
    [[ZCSTKPlayer shareInstance] pause];
    FifthVideoPlayViewController *playVC = [[FifthVideoPlayViewController alloc] init];
    playVC.playUrl = [self.modelArr[self.i] playUrl];
    playVC.titleString = [self.modelArr[self.i] title];
    [self presentViewController:playVC animated:YES completion:^{
         
    }];
}


- (void)nextVideo
{
    if (self.i < self.modelArr.count - 1) {
        self.i++;
        UITableView *tableView = [[ShareTableView shareInstance] init];
        tableView.contentOffset = CGPointMake(0, 200 * self.i);
        [tableView reloadData];
    }
    if (self.i > self.modelArr.count - 2) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"加载" object:@"yes" userInfo:nil];
    }

    [self getMainData];
    [self setButtonImage];
}

- (void)lastVideo
{
    if (self.i > 0) {
        self.i--;
        UITableView *tableView = [[ShareTableView shareInstance] init];
        tableView.contentOffset = CGPointMake(0, 200 * self.i);
        [tableView reloadData];
    } else {
        self.i = 0;
    }

    [self getMainData];
    [self setButtonImage];

}

- (void)downLoadAction
{
    NSLog(@"download");
    [AFNetworkHandler downloadFileURL:[self.modelArr[self.i] playUrl]];
}




- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        nil;
    }];
}


- (void)insertAction
{
    Video *videoModel = [NSEntityDescription insertNewObjectForEntityForName:@"Video" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    videoModel.title = [self.modelArr[self.i] title];
    videoModel.category = [self.modelArr[self.i] category];
    videoModel.video_description = [self.modelArr[self.i] video_description];
    NSString *str1 = [self.modelArr[self.i] category];
    NSString *min = [NSString stringWithFormat:@"%02ld", ((FifthVideoModel *)self.modelArr[self.i]).duration.integerValue / 60];
    NSString *sec = [NSString stringWithFormat:@"%02ld", ((FifthVideoModel *)self.modelArr[self.i]).duration.integerValue % 60];
    videoModel.time = [NSString stringWithFormat:@"#%@ / %@′%@″", str1, min, sec];
    videoModel.playUrl = [self.modelArr[self.i] playUrl];
    videoModel.content = [self.modelArr[self.i] video_description];
    videoModel.coverForFeed = [self.modelArr[self.i] coverForFeed];
    [self.coreDataManager saveContext];

}

- (NSMutableArray *)selectVideoModel
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@", [self.modelArr[self.i] title]];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    NSMutableArray *arr = [NSMutableArray arrayWithArray:fetchedObjects];
    
    if (fetchedObjects == nil) {
        return nil;
    }
    return arr;
}

//下载图片
- (void)downImage
{
    SDWebImageDownloader *downLoader = [SDWebImageDownloader sharedDownloader];
    SDImageCache *cache = [SDImageCache sharedImageCache];
    [downLoader downloadImageWithURL:[NSURL URLWithString:[self.modelArr[self.i] coverForFeed]] options:SDWebImageDownloaderUseNSURLCache progress:NULL completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        
        [cache storeImage:image forKey:[self.modelArr[self.i] coverForFeed]];
        
    }];
    
    self.img = [cache imageFromDiskCacheForKey:[self.modelArr[self.i] coverForFeed]];
}

- (void)getMainData
{
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:[self.modelArr[self.i] coverForFeed]] placeholderImage:[UIImage imageNamed:@""]];
    self.imgView.alpha = 0.3;
    [UIView animateWithDuration:1 animations:^{
        self.imgView.alpha = 1;
    }];
    
    [self.bottomImgView setImage:[UIImage imageNamed:@"2"]];
    self.titleLabel.text = [self.modelArr[self.i] title];
    
    NSString *str1 = [self.modelArr[self.i] category];
    NSString *min = [NSString stringWithFormat:@"%02ld", ((FifthVideoModel *)self.modelArr[self.i]).duration.integerValue / 60];
    NSString *sec = [NSString stringWithFormat:@"%02ld", ((FifthVideoModel *)self.modelArr[self.i]).duration.integerValue % 60];
    self.timeLabel.text = [NSString stringWithFormat:@"#%@ / %@′%@″", str1, min, sec];
    [self.fade setText:[self.modelArr[self.i] video_description]];
}

- (void)setButtonImage
{
    if ([[self selectVideoModel] count]) {
        [self.storeBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:0];
    } else {
        [self.storeBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-wodezuiai"] forState:0];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
